package com.wd.jetpack.api.network

import com.alibaba.fastjson.JSON
import com.wd.jetpack.JpApp
import com.wd.jetpack.R
import com.wd.jetpack.model.BaseResponse
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

open class BaseHeaderHandler : RequestHandler {

    override fun onBeforeRequest(request: Request, chain: Interceptor.Chain): Request {
        val builer = chain.request().newBuilder()
        return builer.build()
    }

    @Throws(IOException::class)
    override fun onAfterRequest(response: Response, chain: Interceptor.Chain): Response {
        var e: ApiException? = null

        when {
            401 == response.code() -> e =
                ApiException(401, JpApp.instance().getString(R.string.network_request_err_401))
            403 == response.code() -> e =
                ApiException(403, JpApp.instance().getString(R.string.network_request_err_403))
            404 == response.code() -> e =
                ApiException(404, JpApp.instance().getString(R.string.network_request_err_404))
            503 == response.code() -> e =
                ApiException(503, JpApp.instance().getString(R.string.network_request_err_503))
            response.code() > 300 -> {
                val message = response.body()?.string()
                e = if (message != null) {
                    val baseResponse = JSON.parseObject(message, BaseResponse::class.java)
                    ApiException(response.code(), baseResponse.msg)
                } else {
                    ApiException(
                        response.code(),
                        response.code().toString() + JpApp.instance()
                            .getString(R.string.network_request_err_500)
                    )
                }
            }
        }
        e?.let {
            throw it
        }
        return response
    }
}